﻿namespace LeetCode_Learn
{
    /// <summary>
    /// 冒泡排序
    /// </summary>
    public class Part02_BubbleSort
    {
        public static int[] Sort(int[] arr)
        {
            if (arr == null)
                throw new ArgumentNullException("arr不可为空!");
            if (arr.Length < 2)
                return arr;

            for (int i = arr.Length - 1; i >= 0; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    if (arr[j] > arr[j + 1])
                    {
                        Swap(arr, j, j + 1);
                    }
                }
            }

            return arr;
        }

        private static void Swap(int[] arr, int index1, int index2)
        {
            arr[index1] = arr[index1] ^ arr[index2];
            arr[index2] = arr[index1] ^ arr[index2];
            arr[index1] = arr[index1] ^ arr[index2];
        }
    }
}
